import os
import random
import time
from datetime import datetime
from flask import request, jsonify, current_app
from werkzeug.utils import secure_filename
from . import api_bp

# 从current_app获取db和模型引用
def get_db_and_models():
    db = current_app.db
    Assessment = current_app.Assessment
    User = current_app.User
    return db, Assessment, User

# 提交问卷评估API
@api_bp.route('/assessment/questionnaire', methods=['POST'])
def submit_questionnaire():
    # 获取db和模型引用
    db, Assessment, User = get_db_and_models()
    
    data = request.json
    
    if not data:
        return jsonify({'success': False, 'message': '缺少评估数据'}), 400
    
    # 检查必要字段
    required_fields = ['eyelidSign', 'rightEyeProtrusion', 'leftEyeProtrusion', 'eyeMovement']
    for field in required_fields:
        if field not in data:
            return jsonify({'success': False, 'message': f'缺少{field}字段'}), 400
    
    # 获取用户ID（可选）
    user_id = data.get('userId')
    
    # 创建评估记录
    assessment = Assessment(
        user_id=user_id if user_id else None,
        assessment_type='questionnaire',
        eyelid_sign=data['eyelidSign'],
        right_eye_protrusion=float(data['rightEyeProtrusion']) if data['rightEyeProtrusion'] else None,
        left_eye_protrusion=float(data['leftEyeProtrusion']) if data['leftEyeProtrusion'] else None,
        eye_movement=data['eyeMovement'],
        status='pending'
    )
    
    db.session.add(assessment)
    db.session.commit()
    
    # 异步处理评估（这里简化为同步处理）
    process_assessment(assessment)
    
    return jsonify({
        'success': True,
        'message': '问卷评估提交成功',
        'assessment_id': assessment.id
    })

# 提交拍照评估API
@api_bp.route('/assessment/photo', methods=['POST'])
def submit_photo_assessment():
    # 获取db和模型引用
    db, Assessment, User = get_db_and_models()
    
    # 检查是否有文件上传
    if 'photo' not in request.files:
        return jsonify({'success': False, 'message': '未上传图片'}), 400
    
    file = request.files['photo']
    
    # 检查文件名
    if file.filename == '':
        return jsonify({'success': False, 'message': '未选择图片'}), 400
    
    # 检查文件类型
    if file and allowed_file(file.filename):
        # 生成安全的文件名
        filename = secure_filename(f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{random.randint(1000, 9999)}_{file.filename}")
        
        # 保存文件
        file_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)
        file.save(file_path)
        
        # 获取用户ID（可选）
        user_id = request.form.get('userId')
        
        # 创建评估记录
        assessment = Assessment(
            user_id=user_id if user_id else None,
            assessment_type='photo',
            photo_path=filename,
            status='pending'
        )
        
        db.session.add(assessment)
        db.session.commit()
        
        # 异步处理评估（这里简化为同步处理）
        process_assessment(assessment)
        
        return jsonify({
            'success': True,
            'message': '拍照评估提交成功',
            'assessment_id': assessment.id
        })
    
    return jsonify({'success': False, 'message': '不支持的图片格式'}), 400

# 获取评估结果API
@api_bp.route('/assessment/result/<int:assessment_id>', methods=['GET'])
def get_assessment_result(assessment_id):
    # 获取db和模型引用
    db, Assessment, User = get_db_and_models()
    
    # 查询评估记录
    assessment = Assessment.query.get(assessment_id)
    
    if not assessment:
        return jsonify({'success': False, 'message': '评估记录不存在'}), 404
    
    # 构建返回数据
    result = {
        'id': assessment.id,
        'assessment_type': assessment.assessment_type,
        'status': assessment.status,
        'created_at': assessment.created_at.strftime('%Y-%m-%d %H:%M:%S'),
        'updated_at': assessment.updated_at.strftime('%Y-%m-%d %H:%M:%S')
    }
    
    # 如果评估已完成，添加评估结果
    if assessment.status == 'completed':
        result['cas_score'] = assessment.cas_score
        result['treatment_advice'] = assessment.treatment_advice
    
    return jsonify({'success': True, 'data': result})

# 获取用户评估历史API
@api_bp.route('/assessment/history', methods=['GET'])
def get_assessment_history():
    # 获取db和模型引用
    db, Assessment, User = get_db_and_models()
    
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'success': False, 'message': '缺少用户ID'}), 400
    
    # 查询用户的评估历史，按创建时间倒序排列
    assessments = Assessment.query.filter_by(user_id=user_id).order_by(Assessment.created_at.desc()).all()
    
    # 格式化评估历史数据
    result = []
    for assessment in assessments:
        item = {
            'id': assessment.id,
            'assessment_type': assessment.assessment_type,
            'status': assessment.status,
            'created_at': assessment.created_at.strftime('%Y-%m-%d %H:%M:%S')
        }
        
        # 如果评估已完成，添加评估结果
        if assessment.status == 'completed':
            item['cas_score'] = assessment.cas_score
        
        result.append(item)
    
    return jsonify({'success': True, 'data': result})

# 获取最新评估结果API（用于report页面）
@api_bp.route('/assessment/latest', methods=['GET'])
def get_latest_assessment():
    # 获取db和模型引用
    db, Assessment, User = get_db_and_models()
    
    user_id = request.args.get('user_id')
    
    if not user_id:
        return jsonify({'success': False, 'message': '缺少用户ID'}), 400
    
    # 查询用户的最新评估记录
    assessment = Assessment.query.filter_by(user_id=user_id, status='completed').order_by(Assessment.created_at.desc()).first()
    
    if not assessment:
        return jsonify({'success': False, 'message': '暂无评估记录'}), 404
    
    # 构建返回数据
    result = {
        'cas_score': assessment.cas_score,
        'treatment_advice': assessment.treatment_advice,
        'assessment_type': assessment.assessment_type,
        'created_at': assessment.created_at.strftime('%Y-%m-%d %H:%M:%S')
    }
    
    return jsonify({'success': True, 'data': result})

# 辅助函数：处理评估
def process_assessment(assessment):
    # 获取db引用
    db, _, _ = get_db_and_models()
    
    # 标记为处理中
    assessment.status = 'processing'
    db.session.commit()
    
    # 模拟处理时间
    # time.sleep(2)  # 实际应用中可以取消注释
    
    # 根据评估类型计算CAS评分和生成治疗建议
    if assessment.assessment_type == 'questionnaire':
        # 根据问卷数据计算CAS评分（这里使用简化的算法）
        cas_score = calculate_cas_score_from_questionnaire(assessment)
        
        # 生成治疗建议
        treatment_advice = generate_treatment_advice(cas_score)
        
    else:  # photo assessment
        # 模拟从照片中分析的结果（实际应用中应该使用AI模型进行分析）
        cas_score = round(random.uniform(1.0, 7.0), 1)
        
        # 生成治疗建议
        treatment_advice = generate_treatment_advice(cas_score)
    
    # 更新评估结果
    assessment.cas_score = cas_score
    assessment.treatment_advice = treatment_advice
    assessment.status = 'completed'
    assessment.updated_at = datetime.now()
    
    db.session.commit()

# 辅助函数：根据问卷数据计算CAS评分
def calculate_cas_score_from_questionnaire(assessment):
    # 简化的CAS评分计算算法
    # 实际应用中应该根据医学标准来实现
    score = 0.0
    
    # 眼睑征评分（0-2分）
    if assessment.eyelid_sign == '轻度':
        score += 1.0
    elif assessment.eyelid_sign == '中度':
        score += 1.5
    elif assessment.eyelid_sign == '重度':
        score += 2.0
    
    # 眼球突出度评分（0-3分）
    protrusion = max(assessment.right_eye_protrusion or 0, assessment.left_eye_protrusion or 0)
    if protrusion > 23:
        score += 3.0
    elif protrusion > 21:
        score += 2.0
    elif protrusion > 19:
        score += 1.0
    
    # 眼球运动评分（0-2分）
    if assessment.eye_movement == '轻度受限':
        score += 1.0
    elif assessment.eye_movement == '中度受限':
        score += 1.5
    elif assessment.eye_movement == '重度受限':
        score += 2.0
    
    # 确保分数在0-7范围内
    score = min(max(score, 0.0), 7.0)
    
    return round(score, 1)

# 辅助函数：生成治疗建议
def generate_treatment_advice(cas_score):
    # 根据CAS评分生成治疗建议
    if cas_score < 2.0:
        return '1. 保持良好的用眼习惯，避免长时间使用电子设备；\n2. 注意眼部休息，每使用电脑1小时应休息10-15分钟；\n3. 定期进行眼部检查，建议每6个月一次。'
    elif cas_score < 4.0:
        return '1. 保持良好的用眼习惯，避免长时间使用电子设备；\n2. 注意眼部休息，每使用电脑1小时应休息10-15分钟；\n3. 定期进行眼部检查，建议每3-6个月一次；\n4. 可考虑使用人工泪液缓解眼部不适。'
    elif cas_score < 6.0:
        return '1. 立即就医，进行详细的眼部检查；\n2. 遵循医生建议进行治疗；\n3. 避免长时间用眼，减少电子设备使用；\n4. 定期复诊，密切关注病情变化。'
    else:
        return '1. 立即就医，进行全面的眼部和甲状腺功能检查；\n2. 遵循医生制定的综合治疗方案；\n3. 避免剧烈运动和长时间用眼；\n4. 定期复诊，严格按照医嘱用药；\n5. 如有视力急剧下降或严重疼痛，立即急诊。'

# 辅助函数：检查文件类型
def allowed_file(filename):
    allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in allowed_extensions